import React, { FC, ReactNode, memo, useEffect, useRef, useState } from 'react'
import { NavBar, Toast, Popup, Button } from 'antd-mobile'
import qs from 'qs'
import { getOrderDetailApi } from './api'
import MyOrderDetail from './style'
import { useLocation, useNavigate } from 'react-router-dom'
import dayjs from 'dayjs'
import { RightOutline } from 'antd-mobile-icons'

import { toDataURL } from 'qrcode' // ✅ 新增

interface IProps {
  children?: ReactNode
}

const Detail: FC<IProps> = () => {
  const navigate = useNavigate()

  const [currentStep, setCurrentStep] = useState(2) // 对应“专人服务”
  const steps = ['填写订单', '在线支付', '专人服务', '服务完成']

  const [orderDetail, setOrderDetail] = useState<any>(null)
  const [showPayPopup, setShowPayPopup] = useState(false)
  const [countdown, setCountdown] = useState('')
  const [qrCodeUrl, setQrCodeUrl] = useState<string>('') // ✅ 存二维码 base64 图片

  const orderInfo = {
    serviceName: '就医陪诊（单享）',
    hospital: '武汉中心医院',
    date: '2024-07-28',
    doctor: 'admin',
    patientName: '张三',
    patientPhone: '13397101182',
    address: '北京市',
    request: '耳鼻喉科',
    orderPhone: '13397101182',
    orderTime: '2024-07-28',
    amount: '0.01',
    orderNo: 'O-ccmI#00167',
    customerService: '客服电话'
  }

  const back = () => {
    navigate(-1)
  }

  const { search } = useLocation()
  const obj = qs.parse(search.slice(1))

  // ✅ 获取订单详情
  const handleGetOrderDetail = async () => {
    console.log(obj)
    const result = await getOrderDetailApi(obj.oid as string)
    console.log('订单详情:', result)
    setOrderDetail(result.data)

    // ✅ 如果是待支付状态，生成二维码
    if (result.data.trade_state === '待支付' && result.data.code_url) {
      const url = await toDataURL(result.data.code_url)
      setQrCodeUrl(url)
      startCountdown(result.data.order_start_time)
      setCurrentStep(1)
    }
    if (result.data.trade_state === '已完成') {
      setCurrentStep(3)
    }
  }

  // ✅ 倒计时逻辑（2小时内支付）
  const countdownTimerRef = useRef<number | null>(null)
  const startCountdown = (startTime: number) => {
    if (countdownTimerRef.current) {
      clearInterval(countdownTimerRef.current)
    }
    const timer = window.setInterval(() => {
      const end = startTime + 2 * 60 * 60 * 1000
      const diff = end - Date.now()
      if (diff <= 0) {
        clearInterval(timer)
        setCountdown('已超时')
        Toast.show({ content: '支付已超时' })
        return
      }
      const h = Math.floor(diff / 1000 / 60 / 60)
      const m = Math.floor((diff / 1000 / 60) % 60)
      const s = Math.floor((diff / 1000) % 60)
      setCountdown(
        `${h.toString().padStart(2, '0')}:${m
          .toString()
          .padStart(2, '0')}:${s.toString().padStart(2, '0')}`
      )
    }, 1000)
    countdownTimerRef.current = timer
  }

  useEffect(() => {
    handleGetOrderDetail()
    return () => {
      if (countdownTimerRef.current) {
        clearInterval(countdownTimerRef.current)
      }
    }
  }, [])

  // 没有请求结果时不渲染
  if (!orderDetail) return null

  const handleGoMyOrder = () => {
    setShowPayPopup(false)
    Toast.show({ content: '一秒后自动跳转订单页' })
    setTimeout(() => {
      navigate('/pz/order')
    }, 1000)
  }
  return (
    <MyOrderDetail>
      <div className="order-detail">
        <NavBar onBack={back}>订单详情</NavBar>

        {/* 顶部进度条 */}
        <div className="progress-bar">
          <div className="line-bg">
            <div
              className="line-fill"
              style={{ width: `${(currentStep / (steps.length - 1)) * 100}%` }}
            ></div>
          </div>
          <div className="step-list">
            {steps.map((step, index) => (
              <div
                key={step}
                className={`step-item ${index <= currentStep ? 'active' : ''}`}
                onClick={() => setCurrentStep(index)}
              >
                <div className="circle">{index + 1}</div>
                <div className="label">{step}</div>
              </div>
            ))}
          </div>
        </div>

        {/* ✅ 如果是待支付状态 */}
        {orderDetail.trade_state === '待支付' ? (
          <div className="pay-box">
            <div className="pay-title">订单待支付</div>
            <div className="pay-amount">¥ {orderInfo.amount}</div>
            <div className="pay-countdown">
              剩余支付时间：{countdown || '加载中...'}
            </div>
            <div className="pay-btn" onClick={() => setShowPayPopup(true)}>
              立即支付
            </div>
          </div>
        ) : orderDetail.trade_state === '已取消' ? (
          <div className="status-box">
            <div className="status-title">您的订单已取消</div>
          </div>
        ) : orderDetail.trade_state === '已完成' ? (
          <div className="status-box">
            <div className="status-title">您的订单已完成，感谢支持！</div>
          </div>
        ) : (
          // ✅ 其他状态维持原样
          <div className="status-box">
            <div className="status-title">正在为您安排服务专员...</div>
            <div className="status-sub">
              请保持手机畅通，稍后有服务专员与您联系
            </div>
          </div>
        )}

        {/* ✅ 二维码弹窗 */}
        <Popup
          visible={showPayPopup}
          onMaskClick={() => setShowPayPopup(false)}
          bodyStyle={{
            borderTopLeftRadius: '16px',
            borderTopRightRadius: '16px',
            minHeight: '40vh',
            textAlign: 'center'
          }}
        >
          <div className="popup-title">微信扫码支付</div>
          {qrCodeUrl ? (
            <img
              src={qrCodeUrl}
              alt="支付二维码"
              style={{
                width: 180,
                height: 180,
                margin: '10px auto',
                borderRadius: '8px'
              }}
            />
          ) : (
            <div>二维码生成中...</div>
          )}
          <div className="popup-desc">请使用微信扫码完成支付</div>
          <Button
            onClick={handleGoMyOrder}
            block
            color="primary"
            style={{ marginTop: '10px' }}
          >
            支付完成后点击
          </Button>
        </Popup>

        {/* 预约信息 */}
        <div className="card">
          <div className="section-title">预约信息</div>
          <div className="info-item">
            <span>预约服务</span>
            <span>就医陪诊（尊享）</span>
          </div>
          <div className="info-item">
            <span>就诊医院</span>
            <span>{orderDetail.hospital_name}</span>
          </div>
          <div className="info-item">
            <span>预留就诊时间</span>
            <span>{orderDetail.starttime}</span>
          </div>
          {/* <div className="info-item">
            <span>陪诊师</span>
            <span>{orderDetail.client.name}</span>
          </div> */}
          <div className="info-item">
            <span>就诊人</span>
            <span>{orderDetail.client.name}</span>
          </div>
          <div className="info-item">
            <span>就诊人电话</span>
            <span>{orderDetail.client.mobile}</span>
          </div>
          <div className="info-item">
            <span>接送地址</span>
            <span>{orderDetail.receiveAddress}</span>
          </div>
          <div className="info-item">
            <span>其他需求</span>
            <span>{orderDetail.demand}</span>
          </div>
        </div>

        {/* 订单信息 */}
        <div className="card">
          <div className="section-title">订单信息</div>
          <div className="info-item">
            <span>联系电话</span>
            <span>{orderDetail.client.mobile}</span>
          </div>
          <div className="info-item">
            <span>下单时间</span>
            <span>
              {dayjs(orderDetail.order_start_time).format('YYYY-MM-DD HH:mm')}
            </span>
          </div>
          <div className="info-item">
            <span>应付金额</span>
            <span>{orderDetail.price}</span>
          </div>
          <div className="info-item">
            <span>订单编号</span>
            <span>{orderDetail.out_trade_no}</span>
          </div>
          <div className="info-item">
            <span>联系客服</span>
            <span className="link">
              疑问或投诉
              <RightOutline />
            </span>
          </div>
        </div>
      </div>
    </MyOrderDetail>
  )
}

export default memo(Detail)
